<template>
	<view>
		<!-- <uni-nav-bar shadow="false" left-icon="back" left-text="取消" right-text="完成" title="添加资源" @click-left="goBack"></uni-nav-bar> -->
		<view class="header-nav">
			<view class="left-btn" @click="goBack">
				<uni-icon type="arrowleft" size="24" style="font-size:52upx" color="#007aff"></uni-icon>
				<view style="color:#007aff">取消</view>
			</view>
			<view>添加资源</view>
			<view style="margin-top:24upx;margin-right:16upx;" @tap="finish">

				<button type="primary" size="mini" style="font-size: 24upx;">完成</button>

			</view>
		</view>

		<view>
			<view>
				<form @submit="formSubmit" @reset="formReset">
					<view class="uni-form-item">
						<view class="title">视频名称</view>
						<input class="uni-input" name="input1" type="text" placeholder="广告视频名称" />
					</view>

					<view class="uni-form-item">
						<view class="title">所属行业</view>
						<view class="uni-list-cell-db">
							<picker name="picker" @change="bindPickerChange" mode=selector :value="index"
								range-key="name" :range="industry">
								<view class="uni-input">{{ industry[index].name }}</view>
							</picker>
						</view>
					</view>


					<view class="uni-form-item">
						<view class="title">视频资源</view>
						<view @tap="test">
							<uni-icon type="redo" color="#007aff" size="48upx"></uni-icon>上传文件
						</view>
					</view>



					<view class="uni-form-item">
						<view class="title">视频时长</view>
						<view>{{temp.time_length}}&nbsp;秒</view>
					</view>

					<view class="uni-form-item">
						<view class="title">视频比例</view>
						<view>{{temp.video_ratio}}</view>
					</view>

					<view class="uni-form-item">
						<view class="title">视频分辨率</view>
						<view>{{temp.video_px}}</view>
					</view>

					<view class="uni-form-item">
						<view class="title">制作单位</view>
						<input class="uni-input" name="input2" type="text" placeholder="制作单位名称" />
					</view>

					<view class="uni-form-item">
						<view class="title">视频描述</view>
						<input class="uni-input" name="input3" type="text" placeholder="视频描述" />
					</view>
					<button form-type="submit">添加完成</button>
				</form>

			</view>
		</view>



		<view>
			<video id="video_hideen" ref="video_hideen" @waiting="aaa" :src="temp.url"></video>
		</view>







	</view>
</template>

<script>
	import uniIcon from "@/components/uni-icon/uni-icon.vue";
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
	import socket from 'plus-websocket';
	import axios from "axios";

	var _self;
	export default {
		components: {
			uniNavBar,
			uniIcon,
		},
		data() {
			return {
				inputValue: '',
				array: ['中国', '美国', '巴西', '日本'],
				index: 0,
				industry: [{ id: '', name: '' }],
				temp: {
					name: '',
					ad_id: "53",
					ad_name: '测001',
					url: "",
					time_length: '',
					trade_id: "",
					trade_name: "",
					producer: "",
					describe: "",
					video_ratio: "",
					video_px: "",
				},

			};
		},
		onLoad() {
			_self = this;
			_self.industryList()
		},
		methods: {

			goBack() {
				uni.switchTab({
					url: '../advertisement/advertisement'
				});
			},
			finish() {
				uni.navigateTo({
					url: '../advertisement/addResult'
				});
			},
			onKeyInput: function (event) {
				this.inputValue = event.target.value;
			},
			//点击行业选择
			bindPickerChange: function (e) {
				console.log('picker发送选择改变，携带值为', e.target.value, this.industry[e.target.value]);
				//value 每一项的值表示选择了 range 对应项中的第几个（下标从 0 开始）
				this.index = e.target.value;
			},
			//行业列表
			industryList() {
				const getTrade = {
					company: 'STQ',
					api: "pc_trade_index",
					version: '1.0',
					data: {
						rows: 20,
						page: 1
					}
				};
				socket.sendSocketMessage({
					data: JSON.stringify(getTrade)
				});

				_self.getData()

			},
			//上传视频
			test() {
				let pathurl = 'http://tv.kdtyun.com/ad1/public/index.php?s=api/index/uploadVideo';//上传服务器地址
				uni.chooseVideo({
					count: 1,
					sourceType: ['camera', 'album'],//从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
					success: function (res) {
						console.log(res)
						const tempFilePaths = res.tempFilePath;
						const size = res.size;
						const audioElement = new Audio(tempFilePaths);
						setTimeout(() => {
							if (audioElement.duration) {
								console.log(parseInt(audioElement.duration))
								_self.temp.time_length = parseInt(audioElement.duration);
							} else {
								console.log('上传的不是视频，没有秒数')
								// _self.temp.time_length = 0;
							}
						}, 500);

						if (size <= 200 * 1024 * 1024) {
							uni.uploadFile({
								url: pathurl,
								fileType: "video",
								filePath: tempFilePaths,
								name: 'video',
								formData: {},
								method: "POST",
								success: (uploadFileRes) => {
									const uploadFileResu = JSON.parse(uploadFileRes.data).data;
									// console.log(uploadFileResu);
									_self.temp.url = uploadFileResu.video_url;

									const video = document.querySelector(".uni-video-video");

									video.addEventListener("canplay", function () {

										function reductionTo(m, n) {
											if (!isInteger(m) || !isInteger(n)) {
												return false;
											} else if (m <= 0 || n <= 0) {
												return false;
											}
											var a = m;
											var b = n;
											a >= b ? ((a = m), (b = n)) : ((a = n), (b = m));
											if (m !== 1 && n !== 1) {
												for (var i = b; i >= 2; i--) {
													if (m % i === 0 && n % i === 0) {
														m = m / i;
														n = n / i;
													}
												}
											}
											return m + ":" + n;
										}
										function isInteger(obj) {
											return obj % 1 === 0;
										}
										_self.temp.time_length = parseInt(this.duration);
										_self.temp.video_ratio = reductionTo(
											this.videoWidth,
											this.videoHeight
										);
										_self.temp.video_px = this.videoWidth + "*" + this.videoHeight;

									});


								},
								fail: function (res) {
									console.log(res)
								}
							});
						} else {
							uni.showToast({
								title: "视频大小不得超过200MB",
								icon: 'none',
								duration: 2000,
								position: 'center'
							});
						}

					},
					fail: function (res) {
						console.log(res)
					}
				});
			},

			getData() {
				socket.onSocketMessage(function (res) {
					if (res !== '{"type":"ping"}') {
						const resj = JSON.parse(res.data);
						if (resj.code === -1) {
							uni.showToast({
								title: resj.message,
								icon: 'none',
								duration: 2000,
								position: 'center'
							});
						} else {
							if (resj.api === "pc_trade_index") {
								const list = []
								resj.data.map(item => {
									return list.push({ name: item.name, id: item.id });
									// return list.push(item.name)
								})
								_self.industry = list
								// console.log(resj.data)
								console.log(_self.industry)
							} else if (resj.api === "pc_AdVideo_addVideo") {
								console.log(resj)
								// if (resj.code === 10000) {
								// 	uni.showToast({
								// 		title: resj.message,
								// 		icon: 'none',
								// 		duration: 2000,
								// 		position: 'center'
								// 	});
								// }
							}


						}
					}
				})
			},
			formSubmit: function (e) {



				console.log('form发生了submit事件，携带数据为：', e.detail.value);



				this.temp.name = e.detail.value.input1;
				this.temp.trade_name = this.industry[e.detail.value.picker].name;
				this.temp.trade_id = this.industry[e.detail.value.picker].id;
				this.temp.producer = e.detail.value.input2;
				this.temp.describe = e.detail.value.input3;

				console.log(this.temp)
				//添加视频资源
				const addVideo = {
					company: 'STQ',
					api: "pc_AdVideo_addVideo",
					version: '1.0',
					data: this.temp
				};
				socket.sendSocketMessage({
					data: JSON.stringify(addVideo)
				});
				_self.getData()


			},
			formReset: function (e) {
				console.log('清空数据');
			},
			videoErrorCallback: function (e) {
				uni.showModal({
					content: e.target.errMsg,
					showCancel: false
				})
			},


		}
	};
</script>

<style>
	.header-nav {
		background-color: #F8F8F8;
		display: flex;
		flex: 1;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		text-align: center;
		width: 100%;
		height: 80upx;
		line-height: 80upx;
		font-size: 30upx;

	}

	.left-btn {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.uni-form-item {
		display: flex;
		flex-direction: row;
		padding: 20rpx;
		font-size: 28rpx;
	}

	.uni-input {
		font-size: 28rpx;
	}

	.uni-form-item .title {
		margin-right: 60rpx;
	}

	.upload-btn {
		border: 1px solid #999999;
		height: 48upx;
		border-radius: 12upx;
		padding: 4upx 6upx;
		line-height: 48upx;
		margin-top: -14upx;
		font-size: 28rpx;
		display: flex;
	}
</style>